package com.healthy.controller.pc;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.config.AlipayConfig;
import com.github.pagehelper.util.StringUtil;
import com.healthy.entity.YgWallet;
import com.healthy.service.YgWalletService;
import com.healthy.util.AlipayUtil;
import com.healthy.util.Dateutil;

/**
 * @author ?????
 * @date 2020年6月12日
 * @description <p>支付所使用的的接口</p>
 */
@RestController
public class YgPayController {

	@Autowired
	private YgWalletService ygWalletService;
	
	// 用户支付统一接口
	@RequestMapping(value = "testpay", method = RequestMethod.GET )
	public void pay1(HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException{
		String CHARSET = AlipayConfig.CHARSET;
		// （可选）公用回传参数
		String PASSBACK_PARAM = "merchantBizType%3d3C%26merchantBizNo%3d201601011111";
		// （可选）业务扩展参数
		JSONObject extends_params = new JSONObject();
		// 全部键值对存储成字符串
		String uid = StringUtils.isEmpty(request.getParameter("uid")) ? null : request.getParameter("uid");
		String money = StringUtils.isEmpty(request.getParameter("money")) ? null : request.getParameter("money");
		String return_url = StringUtils.isEmpty(request.getParameter("return_url")) ? null : request.getParameter("return_url");
		// 如果参数不足，则接口无法成功调用
		if(uid != null || money != null){
			extends_params.put("uid", uid);
			extends_params.put("money", money);
			String EXTENDS_PARAM = extends_params.toJSONString();
	    	AlipayUtil au = new AlipayUtil();
	    	String form = au.sponserPay("用户充值", "用户充值到益果账户", money, "2m", return_url, "notifyUU", PASSBACK_PARAM, EXTENDS_PARAM);
	    	if ( !"".equals(form) ){
	    		response.setContentType( "text/html;charset="  + CHARSET);
	    	    response.getWriter().write(form); //直接将完整的表单html输出到页面 
	    	    response.getWriter().flush();
	    	    response.getWriter().close();
	    	}
		}
	}
	
	// 用户支付异步回调接口之一：余额充值回调
	@RequestMapping(value = "notifyUU", method = RequestMethod.POST )
	public void notify1( HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException{
		Map<String, String> params = AlipayUtil.verify(request);
        if (params != null ) {
        	/*
             * 获得一些信息，可以存入数据库
             */
            // 支付宝交易号
            String trade_no = params.get("trade_no");
            // 商户订单号
            String out_trade_no = params.get("out_trade_no");
            // 收款支付宝账号对应的支付宝唯一用户号。 以2088开头的纯16位数字
            String seller_id  = params.get("seller_id");
            // 交易金额
            String total_amount = params.get("total_amount");
            // 商户原始订单号，最大限制32位
            String merchant_order_no = params.get("merchant_order_no");
            // 买家账号
            String buyer_id = params.get("buyer_id");
            // 打印业务扩展参数
            String passback_params = params.get("passback_params");
            JSONObject jsonObject = JSONObject.parseObject(passback_params.split("@#@")[1]); 
            String uid = jsonObject.getString("uid");
            String money = jsonObject.getString("money");
            BigDecimal charge = new BigDecimal(money);
            YgWallet yw = new YgWallet();
            yw.setId(uid);
            yw.setSurplus(charge);
            boolean success = ygWalletService.updateUserSurplus(yw);
            // 如果数据持久化入库不成功，则退还用户支付的金额
            if( ! success ){
            	System.out.println("系统内部发生错误，正在退款");
            	String out_request_no = Dateutil.getTimeStampString() + buyer_id +"_refund";
            	String msg = "系统内部发生错误，正在退款";
            	AlipayUtil.refund(trade_no, out_trade_no, total_amount, msg, out_request_no);
            }
        }
	}
	

	
}
